package com.i360day.invoker.hystrix;

import com.i360day.invoker.context.HttpInvokerContext;
import org.springframework.util.Assert;

/**
 * @description: 回调
 * @author: liju.z
 * @create: 2019-10-27 10:31
 **/
public class DefaultHystrixMethodInterceptor<T> implements FallbackFactory {

    private Class<?> fallbackClazz;
    private Object fallbackService;

    public DefaultHystrixMethodInterceptor(Class<?> fallbackClazz, HttpInvokerContext httpInvokerContext) {
        this.fallbackClazz = fallbackClazz;
        try {
            this.fallbackService = httpInvokerContext.getBean(fallbackClazz);
        } catch (Exception ex) {
            //ignore
        }
    }

    @Override
    public Object create(Throwable throwable) {
        try {
            //如果获取不到，重新实例化一个
            if (fallbackService == null) {
                Assert.isTrue(!fallbackClazz.isInterface(), fallbackClazz.getName() + " can only be specified on an service");
                return fallbackClazz.getConstructor().newInstance();
            }
            return fallbackService;
        } catch (Throwable ex) {
            throw new IllegalStateException(ex);
        }
    }
}
